import { useUserStore } from '@/stores/modules/user'
import { nextTick } from 'vue'
import { createRouter, createWebHistory } from 'vue-router'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    { path: '/', redirect: '/login' },
    { path: '/login', component: () => import('@/views/login/login.vue') },
    { path: '/register', component: () => import('@/views/login/register.vue') },
    {
      name: 'home', path: '/home', component: () => import('@/views/layouts/default.vue'),
      redirect: '/home/dashboard',
      children: [
        {
          name: 'dashboard', path: 'dashboard', component: () => import('@/views/dashboard/index.vue'), meta: {
            icon: 'fas fa-home',
          },
        },
        {
          name: 'users', path: 'users', component: () => import('@/views/users/index.vue'), meta: {
            icon: 'fas fa-user',
          },
        },
        {
          name: 'roles', path: 'roles', component: () => import('@/views/roles/index.vue'), meta: {
            icon: 'fas fa-tools',
          },
        },
        {
          name: 'menus', path: 'menus', component: () => import('@/views/menus/index.vue'), meta: {
            icon: 'fas fa-bars',
          },
        }
      ]
    }
  ],
})

// 导航守卫
router.beforeEach(async (to) => {
  const userStore = useUserStore()//要在里面写，
  // 等待 token 更新
  await nextTick();
  // 如果用户已登录，并且访问的是登录页或注册页，则重定向到主页或其他合适的页面
  if (userStore.token && (to.path === '/login' || to.path === '/register')) {
    return '/home';
  }
  // 如果没有 token，且目标页面不是登录页或注册页，则跳转到登录页
  if (!userStore.token && to.path !== '/login' && to.path !== '/register') {
    // 如果没有token，或者要去的不是登录页或者注册页，则跳转到登录页
    return '/login'
  }
  // 其他情况下允许路由继续
  return true
})

export default router
